package com.qfmy.web.app.service.impl.user;

import com.qfmy.common.exception.BaseException;
import com.qfmy.common.login.LoginUser;
import com.qfmy.common.login.LoginUserHolder;
import com.qfmy.common.result.ResultCodeEnum;
import com.qfmy.model.entity.user.UserCoupon;
import com.qfmy.model.enums.UserCouponStatus;
import com.qfmy.model.vo.user.UserCouponVo;
import com.qfmy.web.app.mapper.user.UserCouponMapper;
import com.qfmy.web.app.service.user.UserCouponService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 清风明月
 * @Package com.qfmy.web.app.service.impl.novel
 * @date 2025/10/31
 * @description 用户优惠卷
 */
@Service
public class UserCouponServiceImpl implements UserCouponService {

    /**
     * 注入mapper
     */
    @Autowired
    private UserCouponMapper userCouponMapper;

    /**
     * 根据优惠卷类型获取优惠卷
     * @param type
     * @return
     */
    @Override
    public List<UserCouponVo> getUserCouponByType(Integer type) {
        //获取用户id
        Long userId = getUserId();

        //判断用户id是否小于0
        if(userId < 0)
        {
            return Collections.emptyList();
        }
        //查询数据库
        List<UserCoupon> userCoupons = userCouponMapper.getUserCouponByType(type,userId);
        //转换vo
        return convertToVo(userCoupons);
    }

    /**
     * 获取所有优惠券
     * @return
     */
    @Override
    public List<UserCouponVo> getAllCoupon() {
        //获取用户id
        Long userId = getUserId();
        //判断用户id是否小于0
        if(userId < 0)
        {
            return Collections.emptyList();
        }
        //查询数据库
        List<UserCoupon> userCoupons = userCouponMapper.getAllCoupon(userId);
        //转换vo
        return convertToVo(userCoupons);
    }

    /**
     * 转换vo
     * @param userCoupons
     * @return
     */
    private List<UserCouponVo> convertToVo(List<UserCoupon> userCoupons) {
        //判断集合是否为空
        if (userCoupons != null && !userCoupons.isEmpty()) {
            return userCoupons.stream().map(userCoupon -> {
                UserCouponVo userCouponVo = new UserCouponVo();
                BeanUtils.copyProperties(userCoupon, userCouponVo);
                userCouponVo.setStatus(UserCouponStatus.getMessageByStatus(userCoupon.getStatus()));
                return userCouponVo;
            }).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 获取用户id
     */
    private Long getUserId() {
        //获取用户id
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        //判断是否为空
        if (loginUser == null) {
           throw new BaseException(ResultCodeEnum.TOKEN_INVALID);
        }
        return loginUser.getUserId();
    }

}
